package com.example.jwtauthdemo.controller;

import com.example.jwtauthdemo.util.Result;
import com.example.jwtauthdemo.util.ResultCode;

import com.example.jwtauthdemo.dao.Student;
import com.example.jwtauthdemo.vo.StudentApplicationVO;
import com.example.jwtauthdemo.service.StudentManageService;
import com.example.jwtauthdemo.util.JwtUtil;
import com.example.jwtauthdemo.exception.ServiceException;
import com.example.jwtauthdemo.dto.UpdateApplicationStatusRequest;
import com.example.jwtauthdemo.dto.AgreeStudentRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/manageStudent")
public class ManageStudent {
    @Autowired
    private StudentManageService studentManage;

    @Autowired
    private JwtUtil jwtUtil;
    //查询班级学生
    @RequestMapping("/selectStudentInfo")
    @PreAuthorize("hasAnyRole('TEACHER', 'ADMIN')")
    List<Student> selectStudentInfo(String classCode, @RequestHeader("Authorization") String authorizationHeader){
        String jwt = authorizationHeader.substring(7);
        String teacherId = jwtUtil.extractUserId(jwt);
        System.out.println("teacherId: " + teacherId);
        return studentManage.selectStudentInfo(classCode, teacherId);
    }

    //删除学生
    @DeleteMapping("/removeStudent")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<String> removeStudent(String classCode, String studentId, @RequestHeader("Authorization") String authorizationHeader){
        if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer ")) {
            return Result.error(ResultCode.UNAUTHORIZED);
        }
        try {
            String jwt = authorizationHeader.substring(7);
            String teacherIdStr = jwtUtil.extractUserId(jwt);
            if (teacherIdStr == null || teacherIdStr.isEmpty()) {
                return Result.error(ResultCode.TOKEN_INVALID);
            }
            Integer classCodeInt = Integer.parseInt(classCode);
            Integer studentIdInt = Integer.parseInt(studentId);
            Integer teacherId = Integer.parseInt(teacherIdStr);
            int result = studentManage.removeStudent(classCodeInt, studentIdInt, teacherId);
            return Result.<String>success(String.valueOf(result));
        } catch (NumberFormatException e) {
            return Result.error(ResultCode.BAD_REQUEST, "无效的参数格式");
        } catch (Exception e) {
            return Result.error(ResultCode.INTERNAL_SERVER_ERROR);
        }
    }

    //同意学生加入班级
    @PostMapping("/agreeStudent")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<String> agreeStudent(@RequestBody AgreeStudentRequest data, @RequestHeader("Authorization") String authorizationHeader){
        if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer ")) {
            return Result.error(ResultCode.UNAUTHORIZED);
        }
        
        try {
            String jwt = authorizationHeader.substring(7);
            String teacherIdStr = jwtUtil.extractUserId(jwt);
            if (teacherIdStr == null || teacherIdStr.isEmpty()) {
                return Result.error(ResultCode.TOKEN_INVALID);
            }
            
            Integer teacherId = Integer.parseInt(teacherIdStr);
            
            int result = studentManage.agreeStudent(data.getClassCode(), data.getStudentId(), teacherId);
            return Result.<String>success(String.valueOf(result));
        } catch (ServiceException e) {
            return Result.error(e.getCode(), e.getMessage());
        } catch (Exception e) {
            return Result.error(ResultCode.INTERNAL_SERVER_ERROR, "操作失败，请稍后重试");
        }
    }

    //查询待同意的学生申请并关联用户信息
    @GetMapping("/getPendingApplications")
    @PreAuthorize("hasAnyRole('ADMIN')")
    public Result<List<StudentApplicationVO>> getPendingStudentApplications(@RequestHeader("Authorization") String authorizationHeader) {
        if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer ")) {
            return Result.error(ResultCode.UNAUTHORIZED);
        }
        
        try {
            // 提取teacherId
            String jwt = authorizationHeader.substring(7);
            String teacherIdStr = jwtUtil.extractUserId(jwt);
            if (teacherIdStr == null || teacherIdStr.isEmpty()) {
                return Result.error(ResultCode.TOKEN_INVALID);
            }
            
            Integer teacherId = Integer.parseInt(teacherIdStr);
            List<StudentApplicationVO> pendingApplications = studentManage.getPendingStudentApplications(teacherId);
            return Result.success(pendingApplications);
        } catch (ServiceException e) {
            return Result.error(e.getCode(), e.getMessage());
        } catch (Exception e) {
            return Result.error(ResultCode.INTERNAL_SERVER_ERROR, "查询待同意学生申请失败，请稍后重试");
        }
    }
    
    // 更新学生申请班级的状态（同意=1，拒绝=2）
    @PostMapping("/updateApplicationStatus")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<String> updateStudentApplicationStatus(
            @RequestBody UpdateApplicationStatusRequest data, 
            @RequestHeader("Authorization") String authorizationHeader) {
        if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer ")) {
            return Result.error(ResultCode.UNAUTHORIZED);
        }
        
        try {
            // 验证token有效性
            String jwt = authorizationHeader.substring(7);
            if (jwtUtil.extractUserId(jwt) == null) {
                return Result.error(ResultCode.TOKEN_INVALID);
            }
            
            // 调用service层方法更新状态
            int result = studentManage.updateStudentApplicationStatus(data.getUserId(), data.getStatus());
            
            return Result.<String>success("更新成功，影响行数: " + result);
        } catch (ServiceException e) {
            return Result.error(e.getCode(), e.getMessage());
        } catch (Exception e) {
            return Result.error(ResultCode.INTERNAL_SERVER_ERROR, "更新学生申请状态失败，请稍后重试");
        }
    }


    //查询同意或拒绝的学生申请并关联用户信息
    @GetMapping("/getApprovedApplications")
    @PreAuthorize("hasAnyRole('ADMIN')")
    public Result<List<StudentApplicationVO>> getApprovedApplications(@RequestHeader("Authorization") String authorizationHeader) {
        if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer ")) {
            return Result.error(ResultCode.UNAUTHORIZED);
        }
        
        try {
            // 提取teacherId
            String jwt = authorizationHeader.substring(7);
            String teacherIdStr = jwtUtil.extractUserId(jwt);
            if (teacherIdStr == null || teacherIdStr.isEmpty()) {
                return Result.error(ResultCode.TOKEN_INVALID);
            }
            
            Integer teacherId = Integer.parseInt(teacherIdStr);
            List<StudentApplicationVO> approvedApplications = studentManage.getApprovedApplications(teacherId);
            return Result.success(approvedApplications);
        } catch (ServiceException e) {
            return Result.error(e.getCode(), e.getMessage());
        } catch (Exception e) {
            return Result.error(ResultCode.INTERNAL_SERVER_ERROR, "查询已同意或拒绝学生申请失败，请稍后重试");
        }
    }

}
